#!/usr/bin/perl
use strict;
use Digest::MD5;
chdir '/opt/down/ubuntu/dists';
my ($id,$gid)=(getpwnam'sky')[2,3];

my $rel='Release';
my $relg=$rel.'.gpg';

my $showOK=-t STDOUT && $ARGV[0] ne 'nok' ;

my %cmd=('' => '','.gz' => '| gzip -nc9');
my %has;my $ctx=Digest::MD5->new;

foreach my $release (qw/gutsy hardy/)
{
foreach my $dirtail ('',qw/-security -updates -proposed/)
{
    %has=();
    my $dir=$release.$dirtail;
    my ($res,$sz,$file,$has,$ptr);
    next unless -d $dir;
    
    my $in=`gpg --verify $dir/Release.gpg $dir/Release 2>&1`;
    if($?) {print "Broken $dir: $?\n$in"}
    else {print "Dir OK: $dir\n$in" if $showOK}
    
    open IN,"$dir/$rel";
    my %ref=();
    
    while (<IN>)
    {
	next unless /^ (\w{32})\s+(\d+) (\S+)/;
	my ($md0,$s0,$name)=($1,$2,$3);
	$file="$dir/$name";
	next unless $name =~ m{/(binary-i386|source)/};
	$ref{$`}=$file if $name=~/\.gz$/ && !exists($ref{$`});
	$ref{$`}=$file if $name=~/\.bz2$/;
	$has{$file}="$md0/$s0";
    }
    close IN;
    
    foreach my $name (sort keys %ref)
    {
	my $nbz="$dir/$name.bz2";
	my $t=(stat$nbz)[9];
	print("No file: $nbz\n"),next unless $t;
	
	for my $tail (keys %cmd)
	{
	    my $n="$dir/$name$tail";
	    next unless exists $has{$n};

	    unless( -f $n && ($t == (stat _)[9]))
	    {
		print `bunzip2 -cd $nbz $cmd{$tail} > $n`;
		chown $id,$gid,$n;
		utime time(),$t, $n;
		print "Recreated: $n\n";
	    }
	    Hasha($n);
	}
    }

    Hasha($_) foreach sort keys %has;
}
}

sub Hasha($)
{
    my $n=$_[0];
    my $has=$has{$n};
    delete $has{$n};    
    print("No file: $n\n"),return 0 unless -f $n;	
    my $sz=(stat _)[7];
    open FILE,$n;$ctx->addfile(*FILE);close FILE;
    my $dig=sprintf "%s/%u",$ctx->hexdigest,$sz;
    if($dig eq $has)
    {print "OK: $n\n" if $showOK}
    else{my $old=time-365*24*3600;print "$n: $has <> $dig\n";utime $old,$old, $n}
}

__END__    
    	
	(Packages\.bz2|Sources\.bz2|Release)$};
#	my $s1=(stat$in)[7];
	Mirror($file);

	next unless $name =~ m'^(\w+)/binary-i386/Packages\.bz2$' && !$dirtail;
	$file="$dir/$1/i18n/Translation-ru.bz2";
	Mirror($file);
    }
    close IN;
}
